<?php declare(strict_types=1);

namespace App\Api\Handler;

use App\Api\Constants\ErrorCode;
use App\Api\Constants\Business;
use App\Exception\BusinessException;
use App\Helper\RespHelper;
use App\Service\LinkcenterService;
use Hyperf\Support\Traits\StaticInstance;

class SmsCodeHandler
{

    use StaticInstance;

    public function send(array $params): array
    {
        if (empty($params['phone']) || empty($params['business'])) {
            throw new BusinessException(ErrorCode::ERR_PARAMETER, 'Missing parameter of phone number or business');
        }
        if (!phoneValidate($params['phone'])) {
            throw new BusinessException(ErrorCode::ERR_PARAMETER, 'Error parameter of phone number');
        }
        if (!in_array($params['business'], Business::SMS_SCENES)) {
            throw new BusinessException(ErrorCode::ERR_PARAMETER, 'Error parameter of business');
        }
        $code = '666666';
        if (IS_PROD) {
            $sendRes = LinkcenterService::instance()->doRequest(['phone' => $params['phone'], 'business' => $params['business']], '/sms_ali');
            if (!RespHelper::isSucceed($sendRes)) {
                return $sendRes;
            }
            $code = $sendRes['data']['code'];
        }
        return RespHelper::success($code);
    }

}